package ec.cd.client.tracerecorder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;

import ec.cd.common.Sensors;
import ec.cd.common.Sensors.SensorData;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Environment;
import android.util.Log;

public class TraceRecorder implements SensorEventListener {
	private FileWriter outputWriter;
	private int numMessagesRecorded = 0;
	
	private SensorManager sensorManager;
	private Sensor gyroscope;
	private Sensor accelerometer;
	//private List<SensorData> linesToWrite;

	public TraceRecorder(Context context) {
		// TODO Auto-generated constructor stub
		sensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
		accelerometer = sensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		//linesToWrite = new LinkedList<SensorData>();
	}

	protected void startListening(int samplingRate) {
		
		sensorManager.registerListener(this, accelerometer, samplingRate);
		sensorManager.registerListener(this, gyroscope, samplingRate);
	}

	protected void stopListening() {
		sensorManager.unregisterListener(this);
//		try {
//			outputWriter.flush();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		try{
			//write the list to the file
//			for(SensorData event : linesToWrite){
//				String line = event.timestamp + ", " + event.sensorType + ", " +
//						event.values[0] + ", " + event.values[1] + ", " + event.values[2] + "\n";
//				outputWriter.write(line);
//			}
			outputWriter.close();
			System.out.println("Writing succeded!");
			//linesToWrite.clear();
		}catch(Exception ex){
			//ex.printStackTrace();
		}
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	public void onSensorChanged(SensorEvent event) {
		numMessagesRecorded += 1;
		SensorData sensorData = new SensorData();
		sensorData.sensorType = event.sensor.getType();
		sensorData.values = event.values.clone();
		sensorData.timestamp = event.timestamp;
		String line = event.timestamp + ", " + event.sensor.getType() + ", " +
				event.values[0] + ", " + event.values[1] + ", " + event.values[2] + "\n";
		
		//linesToWrite.add(sensorData);
		//System.out.println("A sensor event was received.");
		try{
		outputWriter.write(line);
		//outputWriter.flush();
		}catch(Exception ex){
			//Log.e("CalibrationRecorder", "Could not write to file.");
			//ex.printStackTrace();
			System.exit(0);
		}
	}
	
	public void registerNormalTrace(int samplingRate){
		try {
			File path = Environment.getExternalStoragePublicDirectory(
		            Environment.DIRECTORY_DOWNLOADS);
		    File file = new File(path, "trace"
					+ System.currentTimeMillis() + ".txt");
		    file.createNewFile();
		    
		    outputWriter = new FileWriter(file);
		    startListening(samplingRate);
		} catch (Exception ex) {
			//Log.e("CalibrationRecorder", ex.toString());
			//ex.printStackTrace();
		}
		
	}

	public void registerTraceCalibration(String contextName, int samplingRate) {
		try {
			File path = Environment.getExternalStoragePublicDirectory(
		            Environment.DIRECTORY_DOWNLOADS);
		    File file = new File(path, "calibration"
					+ contextName + System.currentTimeMillis() + ".txt");
		    file.createNewFile();
			
			outputWriter = new FileWriter(file);
			startListening(samplingRate);
		} catch (Exception ex) {
			//Log.e("CalibrationRecorder", ex.toString());
			//ex.printStackTrace();
		}
		
	}

	public int getNumMessagesRecorded() {
		return numMessagesRecorded;
	}

	public void setNumMessagesRecorded(int numMessagesRecorded) {
		this.numMessagesRecorded = numMessagesRecorded;
	}

}
